package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.mongodb.client.MongoCollection;

/**
 * @author li
 */
public class MongoInsertStatement extends AbstractMongoStatement {
    private static final Logger log = Slf4j.getLogger();

    public void execute(PreparedStatement preparedStatement) {
        BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
        MongoCollection<Document> mongoCollection = this.getMongoCollection(mongoPreparedStatement);
        Map<String, Object> statementDocument = this.getStatementDocumentWithParameterValues(mongoPreparedStatement.getParameterMap());

        log.debug("execute(), statementDocument={}, sql={}, parameterMap={}", statementDocument, this.sql(), mongoPreparedStatement.getParameterMap());

        List<Map<String, Object>> insertDocuments = (List<Map<String, Object>>) statementDocument.get(INSERT_VALUES);
        List<Document> documents = new ArrayList<Document>();
        for (Map<String, Object> insertDocument : insertDocuments) {
            documents.add(new Document(insertDocument));
        }

        mongoCollection.insertMany(documents);
        mongoPreparedStatement.updateCount(documents.size());
    }
}